package com.loong.musicdemo.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;

import androidx.core.app.NotificationCompat;

import com.loong.musicdemo.R;
import com.loong.musicdemo.model.LocalPlay;
import com.loong.musicdemo.model.Song;
import com.loong.musicdemo.ui.account.MyCenter.LocalMusicActivity;
import com.loong.musicdemo.util.dataDeal.MusicDeal;
import com.loong.musicdemo.util.downloadutil.DownloadListener;
import com.loong.musicdemo.util.downloadutil.DownloadTask;

import org.litepal.LitePal;

import java.util.Iterator;
import java.util.List;

/**
 * 下载服务
 */
public class DownloadService extends Service {

    private DownloadTask downloadTask;
    private List<String> songIds;//需要下载的歌曲的id
    private int failedCount = 0;//下载失败个数
    private int successCount = 0;//下载成功个数
    private int skipCount = 0;//跳过下载的个数
    private DownloadListener listener = new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            //进度刷新
            getNotificationManager().notify(1, getNotification("Downloading...", progress));
        }

        @Override
        public void onSuccess() {
            successCount++;
            //删除当前项
            if (songIds != null && songIds.size() > 0) {
                String id = songIds.get(0);
                //添加到数据库
                new Thread(() -> {
                    LocalPlay play = new LocalPlay();
                    Song info = MusicDeal.getSongInfoById(id);
                    play.setSongId(id);
                    play.setSongName(info.getName());
                    play.setAuthorName(info.getSingerName());
                    play.save();//下载信息存入数据库
                }).start();
                songIds.remove(0);
            }
            if (songIds != null) {
                for (String id : songIds) {
                    List<LocalPlay> plays = LitePal.where("songId = ?", id).find(LocalPlay.class);
                    if (plays != null && plays.size() != 0) {
                        skipCount++;//跳过的歌曲数目
                        songIds.remove(0);
                    }
                }
            }
            if (songIds == null || songIds.size() == 0) {//全部下载完成
                //下载成功
                downloadTask = null;
                stopForeground(true);
                getNotificationManager().notify(1, getNotification("共计下载成功" + successCount + "首，失败" + failedCount + "首歌！跳过" + skipCount + "首！", -1));
            } else {
                downloadTask = new DownloadTask(listener);
                downloadTask.execute(songIds.get(0));
                getNotificationManager().notify(1, getNotification("开始下载" + songIds.get(0), 0));
            }
        }

        @Override
        public void onFailed() {
            failedCount++;
            //删除当前项
            if (songIds != null && songIds.size() > 0) {
                songIds.remove(0);
            }
            if (songIds != null) {
                for (String id : songIds) {
                    List<LocalPlay> plays = LitePal.where("songId = ?", id).find(LocalPlay.class);
                    if (plays != null && plays.size() != 0) {
                        skipCount++;//跳过的歌曲数目
                        songIds.remove(0);
                    }
                }
            }
            if (songIds == null || songIds.size() == 0) {//已经全部完成下载
                //下载失败
                downloadTask = null;
                stopForeground(true);
                getNotificationManager().notify(1, getNotification("共计下载成功" + successCount + "首，失败" + failedCount + "首歌！跳过" + skipCount + "首！", -1));
            } else {
                downloadTask = new DownloadTask(listener);
                downloadTask.execute(songIds.get(0));
                getNotificationManager().notify(1, getNotification("开始下载" + songIds.get(0), 0));
            }
        }

        @Override
        public void onPaused() {//暂停
            downloadTask = null;
        }

        @Override
        public void onCanceled() {//取消
            downloadTask = null;
            stopForeground(true);
        }
    };

    public DownloadService() {
    }

    private IBinder binder = new DownloadBinder();

    public class DownloadBinder extends Binder {

        public void startDownload(List<String> url) {
            successCount = 0;
            failedCount = 0;
            skipCount = 0;//下载数据清零
            if (downloadTask == null) {
                //id
                songIds = url;
                Iterator<String> iterator = songIds.iterator();
                while (iterator.hasNext()) {
                    String id = iterator.next();
                    List<LocalPlay> plays = LitePal.where("songId = ?", id).find(LocalPlay.class);
                    if (plays != null && plays.size() != 0) {
                        skipCount++;//跳过的歌曲数目
                        iterator.remove();
                    }
                }
                if (songIds.size() != 0) {
                    downloadTask = new DownloadTask(listener);
                    downloadTask.execute(url.get(0));
                    startForeground(1, getNotification("Downloading...", 0));
                }
            }
        }

        public void pauseDownload() {
            if (downloadTask != null) {
                downloadTask.pauseDownload();
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private Notification getNotification(String title, int progress) {
        Intent intent = new Intent(this, LocalMusicActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        if (progress > 0) {
            //显示进度
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
        return builder.build();
    }

}
